from rest_framework.exceptions import ValidationError

from .models import ProblemToTag, AgreeOppositeAnwser


class ProblemToTagValidators(object):
    def __init__(self, tag_num, err_msg):
        self.tag_num = tag_num
        self.err_msg = err_msg

    def __call__(self, *args, **kwargs):
        problem = args[0].get('problem')

        tag_num = ProblemToTag.objects.filter(problem=problem).count()
        if tag_num >= self.tag_num:
            raise ValidationError(self.err_msg, code='unique')


class AgreeOppositeValidator(object):
    def __call__(self, *args, **kwargs):
        answer = args[0].get('answer')
        agree = args[0].get('agree')
        user = args[0].get('user')
        opposite = args[0].get('opposite')

        if agree and not opposite:
            if AgreeOppositeAnwser.objects.filter(user=user, answer=answer, agree=True, opposite=False).count():
                raise ValidationError('已点赞，不能重复点赞', code="unique")
            if AgreeOppositeAnwser.objects.filter(user=user, answer=answer, agree=False, opposite=True).count():
                raise ValidationError('已反对，不能点赞', code="unique")
        elif not agree and opposite:
            if AgreeOppositeAnwser.objects.filter(user=user, answer=answer, agree=True, opposite=False).count():
                raise ValidationError('已点赞，不能反对', code="unique")
            if AgreeOppositeAnwser.objects.filter(user=user, answer=answer, agree=False, opposite=True).count():
                raise ValidationError('已反对，不能重复', code="unique")
        else:
            raise ValidationError('不能即点赞又反对', code="unique")
